package algotithm.leetcode.listnode.test142;

/**
 * @author zhouyanxiang
 * @Date 2021-02-2021/2/18-22:02
 * @URL https://leetcode-cn.com/problems/linked-list-cycle-ii/
 * @Title 142. 环形链表 II
 */

import algotithm.leetcode.listnode.ListNode;

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode detectCycle(ListNode head) {
        if (head == null ) {
            return head;
        }
        ListNode slow = head;
        ListNode fast = head;
        while(fast != null) {
            slow = slow.next;
            if (fast.next != null) {
                fast = fast.next.next;
            } else {
                return null;
            }
            if (slow == fast) {
                ListNode pre = head;
                while (pre != slow) {
                    pre = pre.next;
                    slow = slow.next;
                }
                return pre;
            }
        }
        return null;
    }
}
